package com.demo.common.utils;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * json处理工具类
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class JsonUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.registerModule(new Jdk8Module());
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }
    @SneakyThrows
    public static <T> T json2Object(String json, Class<T> clazz) {
        return objectMapper.readValue(json, clazz);
    }

    /**
     * 序列化java对象
     *
     * @param entity
     * @param <T>
     * @return
     */
    @SneakyThrows
    public static <T> String object2Json(T entity) {
        return objectMapper.writeValueAsString(entity);
    }

    @SneakyThrows
    public static <T> T json2Object(String json, TypeReference<T> typeReference) {
        return objectMapper.readValue(json, typeReference);
    }

}
